<?php

namespace app\admin\controller\cms;

use app\api\controller\v2\Score;
use app\api\service\cms\AttachmentService;
use app\api\service\cms\CutWordIndex;
use app\api\service\CommonService;
use app\common\controller\Backend;
use app\admin\model\cms\Plate;
//use app\admin\model\cms\Platepost;
use app\admin\model\User;
use app\admin\model\cms\Channel;
use fast\Tree;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 帖子管理
 *
 * @icon fa fa-circle-o
 */
class Platepost extends Backend
{

    /**
     * Platepost模型对象
     * @var \app\admin\model\cms\Platepost
     */
    protected $model = null;
    protected $searchFields = 'id,postname,postcontent';
//    protected $noNeedRight = ['selectpage_type'];s

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\Platepost;
        $disabledIds = [];
        $tree = Tree::instance();
        $all = collection(Plate::order("list_order desc,id desc")->select())->toArray();
        $tree->init($all, 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'platename');
//        $categorydata = [0 => ['type' => 'all', 'platename' => __('None')]];
        $categorydata = [];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }      
        $userlist = collection(User::order('id desc')->select())->toArray();
        $userdata = [];
        foreach ($userlist as $k => $v) {
            $userdata[$v['id']] = $v;
        }  
        foreach ($all as $k => $v) {
            $all[$k]['name'] = $v['platename'];
        }
        $tree = Tree::instance()->init($all, 'pid');
        $channelOptions = $tree->getTree(0, "<option model='@model_id' value=@id @selected @disabled>@spacer@name</option>", '', $disabledIds);
        $secondChannelOptions = $tree->getTree(0, "<option model='@model_id' value=@id disabled>@spacer@name</option>", '', $disabledIds);
        $this->view->assign('channelOptions', $channelOptions);
        $this->view->assign("userlist", $userdata);
        $this->view->assign("parentList", $categorydata);
    }
     
  /**
     * 移动
     * @param string $ids
     */
    public function move($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        if ($ids) {
            if (!$this->request->isPost()) {
                $this->error(__("Invalid parameters"));
            }
            $channel_id = $this->request->post('channel_id');
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $this->model->where($pk, 'in', $ids);
            $channel = Plate::get($channel_id);
            if ($channel) {
                $channelNums = \app\admin\model\cms\Platepost::
                with('block')
                    ->where('platepost.' . $pk, 'in', $ids)
                    ->where('plateid', '<>', $channel['id'])
                    ->field('plateid,COUNT(*) AS nums')
                    ->group('plateid')
                    ->select();
                $result = $this->model
                    ->where('plateid', '<>', $channel['id'])
                    ->update(['plateid' => $channel_id]);
//            var_dump(Db::getLastSql());exit;
                if ($result) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('No rows were updated'));
            }
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['replytime'] = $params['replytime'] ? : null;
        $result = false;
        $checkUrl = $this->checkUrl($params['postcontent']);//根据url抓取文章
        if ($checkUrl['code'] == 200){
            $params['scraping_text_link'] = $checkUrl['scraping_text_link'];
            $params['postcontent'] = (new CommonService())->contentFiles($checkUrl['content']);//获取文章内容中的文件链接地址,将不是本项目的文件存到本项目中,并更新对应的文件地址
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            //置顶-调整积分
            $score = new Score();//调整积分
            //置顶
            if ($params['top'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'top_score',1,'plate_post');
            }
            //加精
            if ($params['is_jing'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'highlight_score',1,'plate_post');
            }
            //审核
            if ($params['is_audit'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'input_post_score',1,'plate_post');
            }

            //操作分词索引表
            $cut_word_index = new CutWordIndex();
            $cut_word_index->addCutWordIndex($this->model->id,'plate_post');

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            rmdirs(TEMP_PATH, false);//清除模板缓存，不然include没办法显示最新的信息
            $row = $row->toArray();

            $row['file_video_url'] = [];
            if (!empty($row['file_video'])) {
                //查询附件表
                $file_video_url = (new AttachmentService())->getList(['url'=>$row['file_video']]);
                foreach ($file_video_url as $k => $v) {
                    $url = obsurl($v['url']);
                    $row['file_video_url'][] = [
                        'url' => $url,
                        'name' => $v['filename'],
                        'is_image' => isImage($url),
                    ];
                }
            }
            $row['file_video_url'] = json_encode($row['file_video_url'], JSON_UNESCAPED_UNICODE);

            $row['file_audio_url'] = [];
            if (!empty($row['file_audio'])) {
                //查询附件表
                $file_audio_url = (new AttachmentService())->getList(['url'=>$row['file_audio']]);
                foreach ($file_audio_url as $k => $v) {
                    $url = obsurl($v['url']);
                    $row['file_audio_url'][] = [
                        'url' => $url,
                        'name' => $v['filename'],
                        'is_image' => isImage($url),
                    ];
                }
            }
            $row['file_audio_url'] = json_encode($row['file_audio_url'], JSON_UNESCAPED_UNICODE);

            $row['file_data_url'] = [];
            if (!empty($row['file_data'])) {
                //查询附件表
                $file_data_url = (new AttachmentService())->getList(['url'=>$row['file_data']]);
                foreach ($file_data_url as $k => $v) {
                    $url = obsurl($v['url']);
                    $row['file_data_url'][] = [
                        'url' => $url,
                        'name' => $v['filename'],
                        'is_image' => isImage($url),
                    ];
                }
            }
            $row['file_data_url'] = json_encode($row['file_data_url'], JSON_UNESCAPED_UNICODE);

            $row['accessory_url'] = [];
            if (!empty($row['accessory'])) {
                //查询附件表
                $accessory_url = (new AttachmentService())->getList(['url'=>$row['accessory']]);
                foreach ($accessory_url as $k => $v) {
                    $url = obsurl($v['url']);
                    $row['accessory_url'][] = [
                        'url' => $url,
                        'name' => $v['filename'],
                        'is_image' => isImage($url),
                    ];
                }
            }
            $row['accessory_url'] = json_encode($row['accessory_url'], JSON_UNESCAPED_UNICODE);



            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['replytime'] = $params['replytime'] ? : null;
        $checkUrl = $this->checkUrl($params['postcontent']);//根据url抓取文章
        if ($checkUrl['code'] == 200){
            $params['scraping_text_link'] = $checkUrl['scraping_text_link'];
            $params['postcontent'] = $checkUrl['content'];
        }

        //判断提交内容和旧的内容是否不同
        if ($row['postcontent'] != $params['postcontent']){
            $params['postcontent'] = (new CommonService())->contentFiles($params['postcontent']);//获取文章内容中的文件链接地址,将不是本项目的文件存到本项目中,并更新对应的文件地址
        }
        $params['username'] = User::where('id',$params['user_id'])->value('nickname') ?? '';

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            //调整积分
            $score = new Score();//调整积分
            if (isset($params['top'])){
                if ($params['top'] == 1){
                    //置顶增加积分
                    $score->editScore($params['user_id'],$row['id'],'top_score',1,'plate_post');
                }else{
                    //置顶减少积分
                    $score->editScore($params['user_id'],$row['id'],'top_score',2,'plate_post');
                }
            }
            //加精
            if (isset($params['is_jing'])){
                if ($params['is_jing'] == 1){
                    //增加积分
                    $score->editScore($params['user_id'],$row['id'],'highlight_score',1,'plate_post');
                }else{
                    //减少积分
                    $score->editScore($params['user_id'],$row['id'],'highlight_score',2,'plate_post');
                }
            }
            //审核
            if (isset($params['is_audit'])){
                if ($params['is_audit'] == 1){
                    //增加积分
                    $score->editScore($params['user_id'],$row['id'],'input_post_score',1,'plate_post');
                }else{
                    //减少积分
                    $score->editScore($params['user_id'],$row['id'],'input_post_score',2,'plate_post');
                }
            }

            //操作分词索引表
            $cut_word_index = new CutWordIndex();
            $cut_word_index->updateCutWordIndex($row['id'],'plate_post');

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
//        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));

        if (empty($values)) {
            $this->error("数据不能为空");
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;

        Db::startTrans();
        try {
            $score = new Score();//调整积分
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                //审核
                if (isset($values['is_audit'])){
                    if ($values['is_audit'] == 1){
                        //发帖增加积分
                        $score->editScore($item['user_id'],$item['id'],'input_post_score',1,'plate_post');
                    }else{
                        //发帖减少积分
                        $score->editScore($item['user_id'],$item['id'],'input_post_score',2,'plate_post');
                    }
                }
                //置顶
                if (isset($values['top'])){
                    if ($values['top'] == 1){
                        //置顶增加积分
                        $score->editScore($item['user_id'],$item['id'],'top_score',1,'plate_post');//取消发起置顶
                    }else{
                        //置顶减少积分
                        $score->editScore($item['user_id'],$item['id'],'top_score',2,'plate_post');//取消发起置顶
                    }
                }
                //加精
                if (isset($values['is_jing'])){
                    if ($values['is_jing'] == 1){
                        //加精增加积分
                        $score->editScore($item['user_id'],$item['id'],'highlight_score',1,'plate_post');
                    }else{
                        //加精减少积分
                        $score->editScore($item['user_id'],$item['id'],'highlight_score',2,'plate_post');
                    }
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            //实例化分词
            $cut_word_index = new \app\api\service\cms\CutWordIndex();
            foreach ($list as $item) {
                $count += $item->delete();

                //操作分词索引表
                $cut_word_index->delCutWordIndex($item->id,'plate_post');
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
